package com.likou;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: 陈桂明
 * Date: 2025/8/31 15:29
 * Description: q54
 */
public class q54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int up = 0;
        int down = m - 1;
        int left = 0;
        int right = n - 1;
        List<Integer> list = new ArrayList<>();
        while (true) {
            for (int i = left; i <= right; i++) {
                list.add(matrix[up][i]);
            }
            if (up >= down) {
                break;
            }
            up++;

            for (int i = up; i <= down; i++) {
                list.add(matrix[i][right]);
            }
            if (left >= right) {
                break;
            }
            right--;

            for (int i = right; i >= left; i--) {
                list.add(matrix[down][i]);
            }
            if (up >= down) {
                break;
            }
            down--;

            for (int i = down; i >= up; i--) {
                list.add(matrix[i][left]);
            }
            if (left >= right) {
                break;
            }
            left++;
        }

        return list;
    }
}
